import 'dart:io';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/model/system_questions_model.dart';
import 'package:appflutterhomeschool/res/styles.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/ui/widgets/general_page_jump_widget.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';

class AnswerDisplayViewModel extends ChangeNotifier {
  BuildContext me;
  String buttonName = "下一题";
  int pageTage;

  String id;

  List<SystemQuestionsModel> systemQuestions;

  AnswerDisplayViewModel(this.me, this.id, this.pageTage);

  initView() {
    Dio2Utils.getInstance()
        .post(ApiService.getSystemQuestions, {"student_homework_id": id},
            (successCallBack) {
      Map dataMap = successCallBack["data"];
      systemQuestions = [];
      if (dataMap == null) {
        return;
      }
      List listJson = dataMap["system_questions"];

      if (listJson.length < 0) {
        return;
      }
      listJson.forEach((element) {
        systemQuestions.add(SystemQuestionsModel.fromJson(element));
      });
      notifyListeners();
    }, (errorCallBack) {});
  }

  //单选多选点击事件
  choiceOnTap(index) {
    List<Options> options = systemQuestions[pageTage].options;
    if (systemQuestions[pageTage].questionType == "SC") {
      for (int i = 0; i < options.length; i++) {
        options[i].isCorrect = i == index;
      }
    } else {
      options[index].isCorrect = !options[index].isCorrect;
    }

    notifyListeners();
  }

  lastQuestionOnTap() {
    if (pageTage == 0) {
      Fluttertoast.showToast(msg: "已经是第一道题了！");
      return;
    }
    buttonName = "下一题";
    pageTage--;
    notifyListeners();
  }

  nextQuestionOnTap() {
    if (buttonName == "提交") {
      PromptDialogWidgets(me).showPromptDialog(
          title: "是否提交试卷",
          cencel: "否",
          content: "一旦提交不可更改！",
          sure: "是",
          sureOnTap: () {
            List listJson = [];
            List listImage = [];
            systemQuestions.forEach((element) {
              if (element.questionType != "C") {
                List<Options> listoptions2 = [];
                element.options.forEach((element1) {
                  if (element1.isCorrect) {
                    listoptions2.add(element1);
                  }
                });
                Map mapJsontItem = {
                  "question_order": element?.order,
                  "answers": listoptions2.toList(),
                };
                listJson.add(mapJsontItem);
              } else {
                if (element.userImage != null) {
                  listImage = element.userImage;
                }
              }
            });
            Map<String,dynamic> map = {
              "system_answer": listJson.toList(),
              "img": listImage.toList(),
              "student_homework_id": id
            };
            Logger().d(map);
            Dio2Utils.getInstance().post(ApiService.studentSubmitHomework, map,
                (successCallBack) {}, (errorCallBack) {});
            Navigator.pop(me);
          });
      return;
    }
    pageTage++;
    if (pageTage == systemQuestions.length - 1) {
      buttonName = "提交";
    }
  }

  ImagePicker picker = ImagePicker();

  Widget pictureItemWidget(me) {
    return GeneralPageJumpWidget(
      image: "fabu_tupian",
      title: "选择照片：",
      textTitleStyle: TextStyles.textDark37,
      onTap: () =>
          PromptDialogWidgets(me).showaFileDialog(getIndex: (index) async {
        if (index == 2) return;
        PickedFile pickedFile = await ImagePicker().getImage(
            source: index == 0 ? ImageSource.camera : ImageSource.gallery);
        File imageFile = File(pickedFile.path);
        //图片上传 获取链接
        DioUtils.getInstance().uploadFile(imageFile).then((value) {
          systemQuestions[pageTage].userImage.add(value['file_url']);
          notifyListeners();
        });
      }),
    );
  }
}
